<template>
  <el-form
      :model="form"
      label-width="120px"
      ref="profileForm"
      :rules="rules"
      class="user-form"
  >
    <div class="form-title">编辑个人信息</div>

    <div class="tips-box">
      <div class="tips-title">
        <el-icon><InfoFilled /></el-icon>
        <span>头像上传说明</span>
      </div>
      <div class="tips-content">
        1. 支持 JPG/PNG 格式图片<br>
        2. 图片大小不超过 2MB<br>
        3. 最佳尺寸为 300x300 像素
      </div>
    </div>

    <el-form-item label="用户ID">
      <el-input v-model="form.userId" disabled class="form-input" />
    </el-form-item>

    <el-form-item label="用户名">
      <el-input v-model="form.username" disabled class="form-input" />
    </el-form-item>

    <el-form-item label="手机号">
      <el-input v-model="form.mobite" disabled class="form-input" />
    </el-form-item>

    <el-form-item label="头像" prop="avatarImg">
      <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange"
          :accept="'image/*'"
      >
        <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="upload-tip">点击上传新头像</div>
    </el-form-item>

    <el-form-item label="年龄" prop="age">
      <el-input-number
          v-model="form.age"
          :min="12"
          :max="120"
          controls-position="right"
          size="large"
      />
    </el-form-item>

    <el-form-item label="账户余额">
      <el-input v-model="form.balance" disabled class="form-input" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm" size="large" class="submit-btn">提交修改</el-button>
      <el-button @click="$emit('cancel')" size="large" class="cancel-btn">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Plus, InfoFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const props = defineProps({
  userData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['submit', 'cancel']);

const profileForm = ref(null);
const avatarPreview = ref(props.userData.avatarImg || '');
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

const form = reactive({
  userId: props.userData.userId,
  username: props.userData.username,
  mobite: props.userData.mobite,
  age: props.userData.age,
  avatarImg: props.userData.avatarImg,
  balance: props.userData.balance
});

const rules = {
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 12, max: 120, message: '年龄必须在12到120之间', trigger: 'blur' }
  ],
  avatarImg: [
    {
      validator: (rule, value, callback) => {
        callback(); // 移除验证规则，允许不更新头像
      },
      trigger: 'change'
    }
  ]
};

// 处理头像选择
const handleAvatarChange = (file) => {
  // 验证文件类型和大小
  const isImage = file.raw.type.startsWith('image/');
  const isLt2M = file.raw.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  // 创建预览
  const reader = new FileReader();
  reader.onload = (e) => {
    avatarPreview.value = e.target.result;
    form.avatarImg = file.raw; // 存储文件对象用于上传
  };
  reader.readAsDataURL(file.raw);
};

// 提交表单 - 修复版
const submitForm = () => {
  profileForm.value.validate(valid => {
    if (valid) {
      // 创建FormData对象
      const formData = new FormData();

      // 添加年龄
      formData.append('age', form.age);

      // 添加文件（如果存在）
      if (form.avatarImg instanceof File) {
        formData.append('file', form.avatarImg);
      } else {
        // 添加空文件占位符
        formData.append('file', new Blob());
      }
      console.log(formData.get('file'), formData.get('age'));
      // 触发submit事件，传递FormData
      emit('submit', formData);
    } else {
      return false;
    }
  });
};

// 当父组件传递的用户数据变化时更新表单
watch(() => props.userData, (newVal) => {
  Object.assign(form, newVal);
  avatarPreview.value = newVal.avatarImg || defaultAvatar;
}, { deep: true });
</script>

<style scoped>
/* 样式保持不变 */
.user-form {
  padding: 25px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.form-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30px;
  position: relative;
  padding-bottom: 15px;
}

.form-title::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(90deg, #409eff, #e54847);
  border-radius: 2px;
}

.tips-box {
  background-color: #f0f7ff;
  border-left: 4px solid #409eff;
  padding: 16px;
  margin: 0 0 30px;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
}

.tips-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
  font-size: 15px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.tips-content {
  line-height: 1.7;
}

.avatar-uploader {
  border: 2px dashed #dcdfe6;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 140px;
  height: 140px;
  background-color: #f8fafc;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;
}

.avatar-uploader:hover {
  border-color: #409eff;
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.2);
}

.avatar-uploader-icon {
  font-size: 36px;
  color: #c0c4cc;
  transition: color 0.3s;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
  transition: transform 0.3s;
}

.avatar-uploader:hover .avatar {
  transform: scale(1.03);
}

.upload-tip {
  font-size: 13px;
  color: #909399;
  margin-top: 10px;
  padding-left: 5px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 25px;
  margin-top: 40px;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  border: none;
  padding: 12px 35px;
  font-size: 16px;
  transition: all 0.3s;
}

.submit-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.3);
}

.cancel-btn {
  background: linear-gradient(135deg, #e54847, #ff7e7e);
  border: none;
  padding: 12px 35px;
  font-size: 16px;
  color: white;
  transition: all 0.3s;
}

.cancel-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(229, 72, 71, 0.3);
}

.form-input {
  max-width: 300px;
}
</style>